Home:ALL Converter>Binding to a depencency property doesn't work

Binding to a depencency property doesn't work

Ask Time:2012-06-22T04:42:02         Author:Eternal21

Json Formatter

I derived ImageButton from Button class. I want to be able to set text on it using custom property.

ImageButton XAML

<Button x:Class="MyProject.ImageButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="50" Width="75" Template="{DynamicResource BlueButton}">
    <StackPanel>
        <TextBlock Text="{Binding Path = ImageButton.ButtonText}" TextWrapping="Wrap" Foreground="White"/>
    </StackPanel>
</Button>

ImageButton code behind

    public partial class ImageButton : Button
    { 
        public string ButtonText
        {
            get { return (string)GetValue(ButtonTextProperty); }
            set { SetValue(ButtonTextProperty, value); }
        }

        public static readonly DependencyProperty ButtonTextProperty =
            DependencyProperty.Register("ButtonText", typeof(string), typeof(ImageButton), new UIPropertyMetadata(string.Empty));

        public ImageButton()
        {
            InitializeComponent();
        }
    }

Client code:

<local:ImageButton Margin="114,15.879,96,15.878" Grid.Row="2" ButtonText="test"/>

No text is being shown on the button. For some reason the binding doesn't seem to be taking place. What am I doing wrong?

Author:Eternal21,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/11146407/binding-to-a-depencency-property-doesnt-work
Douglas :

You don’t have a DataContext set, so the data binding doesn’t know which source object it should bind to.\n\nI find that the easiest way to resolve this is to give your outer control a name, and reference it using ElementName in your binding:\n\n<Button x:Class=\"MyProject.ImageButton\"\n x:Name=\"myImageButton\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Height=\"50\" Width=\"75\" Template=\"{DynamicResource BlueButton}\">\n <StackPanel>\n <TextBlock Text=\"{Binding ElementName=myImageButton, Path=ButtonText}\" \n TextWrapping=\"Wrap\" Foreground=\"White\"/>\n </StackPanel>\n</Button>\n",
2012-06-21T20:50:55
yy